package com.common.core;

import java.io.BufferedReader;
import java.io.IOException;

import javax.xml.bind.JAXBException;

import com.common.utils.JsonUtil;
import com.jfinal.core.Controller;

/**
 *
 */
public class BaseController extends Controller {

	protected String getControllerKey() {
		return this.getAttr("ControllerKey");
	}

	protected boolean isPost() {
		return "post".equals(getRequest().getMethod().toLowerCase());
	}

	protected void goBack() {
		goBack(-1);
	}

	protected void goBack(int step) {
		renderJS("history.go(" + step + ")");
	}

	protected void alertAndGoback(String msg) {
		alertAndGoback(msg, -1);
	}

	protected void alertAndGoback(String msg, int step) {
		renderJS("alert('" + msg + "');history.go(" + step + ")");
	}

	protected void renderJS(String jsContent) {
		renderHtml("<script type=\"text/javascript\">" + jsContent
				+ "</script>");
	}

	/**
	 * 获取请求数据
	 * 
	 * @param valueType
	 * @return
	 */
	protected <T> T getRequestObject(Class<T> valueType) {
		StringBuilder json = new StringBuilder(1024);
		BufferedReader reader = null;
		try {

			reader = this.getRequest().getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
			
		} catch (Exception e) {
		}finally
		{
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return JsonUtil.fromJson(json.toString(), valueType);
	}
	
	/**
	 * 获取请求数据
	 * 
	 * @param valueType
	 * @return
	 */
	protected <T> T getRequestObject(Class<T> valueType,String dateFromat) {
		StringBuilder json = new StringBuilder(1024);
		BufferedReader reader = null;
		try {

			reader = this.getRequest().getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
			
		} catch (Exception e) {
		}finally
		{
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return JsonUtil.fromJsonDateFromat(json.toString(),dateFromat, valueType);
	}
  
	/**
	 * 获取请求数据
	 * 
	 * @param valueType
	 * @return
	 * @throws JAXBException 
	 */
	protected StringBuilder getRequestStr(){
		
		
		StringBuilder json = new StringBuilder(1024);
		BufferedReader reader = null;
		try {

			reader = this.getRequest().getReader();
			String line = null;
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
	
		} catch (Exception e) {
			System.out.println(e);
		}finally
		{
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return json;
		
	}
}
